package org.example;

import org.example.Enum.ActionEnum;
import org.example.Enum.CisternState;
import org.example.Enum.DispenserState;

import java.util.ArrayList;

/**
 * @program: B1_exper4
 * @description: 状态机
 * @author: hlt
 * @create: 2023-11-04 19:51
 **/
public class StateMachine {
    private ArrayList<StateTranslation> stateTranslationList;  // 当前的状态信息
    private DispenserState currentState;  // 当前状态

    public StateMachine(DispenserState currentState){
        this.currentState = currentState;
        stateTranslationList = new ArrayList<>();
    }

    public DispenserState getCurrentState(){
        return currentState;
    }

    public StateTranslation addStateTranslation(){
        // 配置时新增一条状态转换信息
        StateTranslation stateTranslation = new StateTranslation();
        stateTranslationList.add(stateTranslation);
        return stateTranslation;
    }

    /**
     * 执行状态转换
     * @param actionEnum：当前发生的动作
     * @param cisternState：满足的前提条件
     * @return：返回转换过程，可以根据需求更改
     */
    public StateTranslation execute(ActionEnum actionEnum, CisternState cisternState){
        for (StateTranslation translation : stateTranslationList){
            if (translation.getCurrentState() == currentState   // 在当前状态下
                && translation.getAction() == actionEnum        // 发生了当前动作
                && (translation.getCondition() == cisternState
                    || translation.getCondition() == null || cisternState == null)   /* 满足前提条件, null表示无前提条件 */){
                translation.getEvent().handle(); // 执行相应的动作
                currentState = translation.getNextState(); // 状态转换至下一个状态
                return translation;
            }
        }
        return null;
    }
}
